package com.mzpai.api.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.mzpai.api.vo.StoreSeckillMsgVo;
import com.mzpai.api.vo.StoreSeckillProductVo;
import com.mzpai.api.vo.StoreSeckillVo;
import com.mzpai.product.model.StoreSeckill;
import com.mzpai.product.model.StoreUserSeckillCollect;
import com.mzpai.product.service.StoreOrderService;
import com.mzpai.product.service.StoreProductDescriptionService;
import com.mzpai.product.service.StoreSeckillService;
import com.mzpai.product.service.StoreUserSeckillCollectService;
import com.mzpai.product.vo.StoreOrderVo;
import com.mzpai.util.BeanUtils;
import com.mzpai.util.DateUtil;
import com.mzpai.util.StringUtils;
import com.mzpai.util.UserUtils;
import com.mzpai.vo.ResponseVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
 *
 * 会员信息查询
 *
 */
@Api(value = "用户信息接口")
@RestController
@RequestMapping("/seckill")
public class SeckillController extends BaseController {

	@Autowired 
	private StoreSeckillService storeSeckillService;
	@Autowired 
	private StoreOrderService storeOrderService;
	@Autowired 
	private StoreProductDescriptionService storeProductDescriptionService;
	
	@Autowired 
	private StoreUserSeckillCollectService storeUserSeckillCollectService;
	private static Logger log = LoggerFactory.getLogger(SeckillController.class);
	
	
	@ApiOperation(value = "获取秒杀列表")
    @RequestMapping(value = "/getProductList")
    public ResponseVo<List<StoreSeckillVo>> queryUserInfo(
    		@ApiParam(required = true, name = "storeId", value = "入参为storeId")
    		@RequestParam(value = "storeId", required = true) String storeId,
    		@ApiParam(required = true, name = "userId", value = "入参为userId")
    		@RequestParam(value = "userId", required = false) Integer userId){
		log.info("msg1=开始获取秒杀信息,,method=getProductList,,storeId={},,userId={}",storeId,userId);
		ResponseVo<List<StoreSeckillVo>> resVo = new ResponseVo<List<StoreSeckillVo>>();
		try{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("havaStock", "Y");
			map.put("status", "1");
			map.put("isDel", 0);
			map.put("storeId", storeId);
			map.put("stopTimeValid", "Y");
			List<StoreSeckill> list = storeSeckillService.getList(map);
			List<StoreSeckillVo> voList = new LinkedList<StoreSeckillVo>();
			for(StoreSeckill c : list) {
				StoreSeckillVo vo = new StoreSeckillVo();
				BeanUtils.copy(c, vo);
				
				//校验是否点过想要
				if(userId!=null){
					Integer seckillId=c.getId();
					Map<String,Object> queryMap=new HashMap<String,Object>();
					queryMap.put("storeId", storeId);
					queryMap.put("userId", userId);
					queryMap.put("seckillId", seckillId);
					List<StoreUserSeckillCollect> storeUserSeckillCollectList=storeUserSeckillCollectService.getList(queryMap);
					if(storeUserSeckillCollectList!=null && !storeUserSeckillCollectList.isEmpty()){
						vo.setWantFlage("2");
					}else{
						vo.setWantFlage("1");
					}
				}else{
					vo.setWantFlage("1");
				}
				vo.setStartTime(DateUtil.getUTCDateTime(c.getStartTime()));
				vo.setEndTime(DateUtil.getUTCDateTime(c.getStopTime()));
				vo.setServerTime(DateUtil.getUTCDateTime(new Date()));
				//添加购买人员头像
				addUserSell(vo, c.getId());
				voList.add(vo);
			}
			resVo.setResult(voList);
			
		} catch(Exception e) {
			logger.error("msg1=异常信息， ", e);
		}
		
		log.info("msg1=结束获取秒杀信息,,method=getProductList,,storeId={},,userId={}",storeId,userId);
	    return resVo;
	}
	
	/**
	 * 增加
	 * @param vo
	 * @param id
	 */
	
	private void addUserSell(StoreSeckillVo vo, Integer id) {
		Long nowLong = DateUtil.getUTCDateTime(DateUtil.addMinutes(new Date(), 5));
		logger.info("msg=111111={}", JSONObject.toJSON(vo));
		if(vo.getStartTime() != null && vo.getStartTime().longValue() < nowLong) {
			vo.setUserCount((int)(Math.random() * 50));
			Map<Integer, Integer> map = UserUtils.getRandomUser();
			String temp = "";
			for(Integer i : map.keySet()) {
				temp = temp + UserUtils.userImg.split(",")[i] + ",";
			}
			vo.setUserImg(StringUtils.removeLastChar(temp));
		} else {
			vo.setUserCount(0);
			vo.setUserImg("");
		}
	}


	/**
	 * 进入商品详情
	 * @param id
	 * @return
	 */
	
	@ApiOperation(value = "秒杀列表选择商品进入详情")
    @RequestMapping(value = "/getProductById")
    public ResponseVo<StoreSeckillProductVo> getProductById(
    		@ApiParam(required = true, name = "id", value = "入参为id")
    		@RequestParam(value = "id", required = true) String id){
		log.info("msg1=秒杀列表选择商品进入详情,,method=getProductById,,id={}",id);
		ResponseVo<StoreSeckillProductVo> resVo = new ResponseVo<StoreSeckillProductVo>();
		try{
			StoreSeckill seckill = storeSeckillService.queryByPrimaryId(Integer.parseInt(id));
			StoreSeckillProductVo vo = new StoreSeckillProductVo();
			BeanUtils.copy(seckill, vo);
			vo.setStartTime(DateUtil.getUTCDateTime(seckill.getStartTime()));
			vo.setEndTime(DateUtil.getUTCDateTime(seckill.getStopTime()));
			vo.setServerTime(DateUtil.getUTCDateTime(new Date()));
			//设置图片内容
			vo.setDescList(storeProductDescriptionService.getListByProductId(seckill.getProductId()));
			resVo.setResult(vo);
			
		} catch(Exception e) {
			logger.error("msg1=异常信息， ", e);
		}
	    return resVo;
	}
	
	
	/**
	 * 秒杀人员信息
	 * 6条数据
	 * @return
	 */
	@ApiOperation(value = "获取秒杀人员信息")
    @RequestMapping(value = "/getUserOrderMsg")
    public ResponseVo<List<StoreSeckillMsgVo>> getUserOrderMsg(@ApiParam(required = true, name = "storeId", value = "入参为storeId")
	@RequestParam(value = "storeId", required = true) String storeId){
		log.info("msg1=获取秒杀人员信息,,method=getUserOrderMsg,");
		ResponseVo<List<StoreSeckillMsgVo>> resVo = new ResponseVo<List<StoreSeckillMsgVo>>();
		try{
			//检查是否有开始的秒杀
			if(showMsg(storeId)) {
				resVo.setResult(null);
				return resVo;
			}
			List<StoreSeckillMsgVo> list = new LinkedList<StoreSeckillMsgVo>();
			Map<String, Object> mapVo = new HashMap<String, Object>();
			mapVo.put("storeId", storeId);
			mapVo.put("orderType", "4");
			PageInfo<StoreOrderVo> pageInfo = storeOrderService.getVoListPage(mapVo, 1, 6);
			if(pageInfo != null && pageInfo.getList().size() >= 6) {
				for(StoreOrderVo v : pageInfo.getList()) {
					StoreSeckillMsgVo vo = new StoreSeckillMsgVo();
					vo.setUserImg(v.getAvatar());
					vo.setSim(v.getUserPhone());
					vo.setCount(v.getAttrCount() + "");
					vo.setAmount(v.getPayPrice() + "");
					list.add(vo);
				}
			} else {
				Map<Integer, Integer> map = UserUtils.getRandomUser();
				for(Integer i : map.keySet()) {
					StoreSeckillMsgVo vo = new StoreSeckillMsgVo();
					vo.setUserImg(UserUtils.userImg.split(",")[i]);
					vo.setSim(UserUtils.userSim.split(",")[i] != null ? UserUtils.userSim.split(",")[i].replaceAll("(\\d{2})\\d{6}(\\d{3})","$1******$2"):"132*****011");
					vo.setCount(UserUtils.count.split(",")[i]);
					vo.setAmount(UserUtils.amount.split(",")[i]);
					list.add(vo);
				}
			}
			resVo.setResult(list);
			
		} catch(Exception e) {
			logger.error("msg1=异常信息， ", e);
		}
		
		return resVo;
	}

	private boolean showMsg(String storeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("havaStock", "Y");
		map.put("status", "1");
		map.put("isDel", 0);
		map.put("storeId", storeId);
		map.put("stopTimeValid", "Y");
		//5分钟
		map.put("startTimeFiveMinute", "Y");
		List<StoreSeckill> list = storeSeckillService.getList(map);
		if(list.isEmpty() || list.size() == 0) {
			return true;
		}
		return false;
		
	}
	
	
		

}